package com.limao.servlet;

import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;

import javax.servlet.AsyncContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.limao.AsyncListener.AppAsyncListener;


@WebServlet(name="upload", urlPatterns="/upload",asyncSupported=true)
public class upload extends HttpServlet {

	private static final long serialVersionUID = -4731921955198294524L;
	

	private ServletContext sc;

	@Override
	public void init(ServletConfig config) throws ServletException {
		sc = config.getServletContext();
	}


	public void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	
		
		request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
		request.setCharacterEncoding("UTF-8");
	      
	      //开始异步调用，获取对应的AsyncContext。
	      AsyncContext asyncContext = request.startAsync();
	      //设置当前异步调用对应的监听器
	      asyncContext.addListener(new AppAsyncListener());
	      //设置超时时间，当超时之后程序会尝试重新执行异步任务，即我们新起的线程。
	      asyncContext.setTimeout(120*1000L);
	      //新起线程开始异步调用，start方法不是阻塞式的，它会新起一个线程来启动Runnable接口，之后主程序会继续执行
	      ThreadPoolExecutor executor = (ThreadPoolExecutor) request.getServletContext().getAttribute("executor");
	      executor.execute(new uploadAsyncProcessor(asyncContext, request,response));
		
		
	}
	
}
